package com.innovation.chengzhangriji.ui;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.AllBabyResponse;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.adapter.HomePageAdapter;
import com.innovation.chengzhangriji.ui.agent.HomeActivityAgent;
import com.innovation.chengzhangriji.ui.event.BaseEvent;
import com.innovation.chengzhangriji.ui.widget.CuteViewPager;
import com.innovation.chengzhangriji.ui.widget.HomeTabBar;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;

public class HomeActivity extends BaseActivity implements HomeTabBar.OnCheckChangeListener, HomePageAdapter.HomePageAdapterAgent {

    private HomeTabBar homeTabBar;
    private CuteViewPager viewPager;

    private HomeActivityAgent agent;
    public HomeActivityAgent getAgent() {
        return agent;
    }

    // fragment 列表
    private ArrayList<Fragment> fragments = new ArrayList<>();

    private HomePageAdapter adapter;

    private ImageView imageMsgPoint, imageNotifyPoint;

    private final int REQUEST_CODE_EDIT_DIALOG = 0;
    private final int REQUEST_CODE_EDIT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        // 数据代理
        agent = new HomeActivityAgent(this);

        // 初始化视图
        setupLayout();

        // 注册监听器
        registerBroadcastReceiver();
    }

    // 初始化视图
    private void setupLayout() {

        // TabBar
        homeTabBar = (HomeTabBar) findViewById(R.id.homeTabBar);
        homeTabBar.setOnCheckChangeListener(this);

        // 成长日记
        Fragment czRJFragment = new ChZhRJFragment();
        fragments.add(czRJFragment);

        // 发现
        Fragment findFragment = new FindFragment();
        fragments.add(findFragment);

        // 妈咪说
        Fragment mmsFragment = new MmsFragment();
        fragments.add(mmsFragment);

        // 圈子
        Fragment qzFragment = new QuanZiFragment();
        fragments.add(qzFragment);

        // 我的
        Fragment mineFragment = new MineFragment();
        fragments.add(mineFragment);

        // 切换视图
        viewPager = (CuteViewPager) findViewById(R.id.viewpager);
        adapter = new HomePageAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(adapter);
//        viewPager.setOffscreenPageLimit(1);

        // 新消息
        imageMsgPoint = (ImageView) findViewById(R.id.image_point_msg);

        // 新通知
        imageNotifyPoint = (ImageView) findViewById(R.id.image_point_notify);

        // 检查是否需要完善信息
        if ((TextUtils.isEmpty(mLoginInfo.getName()) || mLoginInfo.getGender() == 0) && !mLoginInfo.isHasTipEdit()) {
            Intent intent = new Intent(this, EditUserInfoDialogActivity.class);
            startActivityForResult(intent, REQUEST_CODE_EDIT_DIALOG);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK) {
            if(requestCode == REQUEST_CODE_EDIT_DIALOG) {
                Intent intent = new Intent(this, EditUserInfoActivity.class);
                startActivityForResult(intent, REQUEST_CODE_EDIT);
            } else if(requestCode == REQUEST_CODE_EDIT) {
                mLoginInfo = Config.getLoginInfo(this);
            }
        }
    }

    // 设置页面
    public void startSettingActivity(View v) {
        startActivity(new Intent(this, SettingsActivity.class));
    }

    // 我的日记本
    public void startMyDiaryActivity(View v) {
        Baby[] babies = DatabaseManager.getInstance(this).queryBabyAll(mLoginInfo.getUserID());
        if(babies == null || babies.length == 0) {
            tipShow("您还没有创建或关注日记本");
        } else {
            startActivity(new Intent(this, MyDiaryActivity.class));
        }
    }

    // 通知页面
    public void startNotificationActivity(View v) {
        Config.cleanHasNewNotify(this);
        showNewNotificationPoint(false);
        startActivity(new Intent(this, MessagesActivity.class));
    }

    // 用户资料页面
    public void startUserInfoActivity(View v) {
        startActivity(new Intent(this, EditUserInfoActivity.class));
    }

    // 注册监听器
    public void registerBroadcastReceiver() {
        LocalBroadcastManager.getInstance(this).registerReceiver(deleteDiaryReceiver, new IntentFilter("delete"));
    }

    // 取消注册监听器
    public void unregisterBroadcastReceiver() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(deleteDiaryReceiver);
    }

    // 删除日记监听器
    BroadcastReceiver deleteDiaryReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 重新请求宝宝信息
            agent.requestAllBabyInfo();
        }
    };

    // 接收消息推送
    @Override
    protected void receiveChZhRJMessage(int type, int tag) {
        // 日记圈消息
        if (type == 1) {
            showNewMessagePoint();
        }
    }

    // 处理
    private Handler mHandler = new Handler();

    @Override
    public void onEvent(BaseEvent event) {
        super.onEvent(event);
        if(event.getType() == BaseEvent.TYPE_SYNC_BABY_INFO) {
            // 获取宝宝所有的关注人的信息
            Config.startGetAllParentInfoService(this);
            refreshDiaryList();
        } else if(event.getType() == BaseEvent.TYPE_NEW_COMMENT_DOWNLOAD_SUCCESS) {
            // 日记圈新消息
            showNewMessagePoint();
        } else if(event.getType() == BaseEvent.TYPE_NEW_NOTIFICATION) {
            // 新通知
            if(event.getState() == 1) {
                showNewNotificationPoint(true);
                refreshDiaryList();
            }
        }
    }

    // 刷新日记本列表
    private void refreshDiaryList() {
        if(fragments != null && fragments.size() > 0) {
            if(fragments.get(0) != null && fragments.get(0) instanceof ChZhRJFragment) {
                // 日记变动后，刷新成长日记列表
                ((ChZhRJFragment) fragments.get(0)).refreshData();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBroadcastReceiver();
    }

    @Override
    public void onCheckChanged(int position) {
        viewPager.setCurrentItem(position, false);
        // 查询服务器是否有新的申请和邀请通知
        agent.requestNewNotification();
    }

    @Override
    protected void onResume() {
        super.onResume();
        agent.onResume();
        // 查询服务器是否有新的申请和邀请通知
        agent.requestNewNotification();
        // 重新获取所有宝宝的信息
        agent.requestAllBabyInfo();
        // 检查是否有新日记或者评论
        showNewMessagePoint();
    }

    // 有新日记或者评论时显示通知
    private void showNewMessagePoint() {
        if(Config.getHasNewMessage(this) || Config.getHasNewComment(this)) {
            imageMsgPoint.setVisibility(View.VISIBLE);
        } else {
            imageMsgPoint.setVisibility(View.INVISIBLE);
        }
        if(fragments != null && fragments.size() > 0) {
            if(fragments.get(1) != null && fragments.get(1) instanceof FindFragment) {
                // 有新通知，显示 new 图标
                ((FindFragment)fragments.get(1)).showNewMsgPoint();
            }
        }
    }

    // 有新通知
    private void showNewNotificationPoint(boolean flag) {
        Config.setHasNewNotify(this, flag);
        if(flag) {
            imageNotifyPoint.setVisibility(View.VISIBLE);
        } else {
            imageNotifyPoint.setVisibility(View.INVISIBLE);
        }
        if(fragments != null && fragments.size() > 0) {
            if(fragments.get(4) != null && fragments.get(4) instanceof MineFragment) {
                // 有新通知，显示 new 图标
                ((MineFragment)fragments.get(4)).showNewNotifyIcon(flag);
            }
        }
    }

    @Override
    public int getFragmentCount() {
        return fragments.size();
    }

    @Override
    public ArrayList<Fragment> getFragments() {
        return fragments;
    }
}
